from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
import json

# Create your views here.
def sign_handle(request):
    request.params = json.loads(request.body)
    action = request.params.get('action')
    if action == 'signin':
        return signin(request)
    elif action == 'signout':
        return signout(request)
    else:
        return JsonResponse({'ret': 1, 'msg': '非法请求'}, json_dumps_params={'ensure_ascii': False})

def signin(request):
    userName = request.params.get('username')
    passWord = request.params.get('password')

    # 使用 Django auth 库里面的方法校验用户名、密码
    user = authenticate(username=userName, password=passWord)

    # 如果能找到用户，并且密码正确
    if user:
        # auth_user表中有个字段【is_active】，值为1或0
        if user.is_active:
            # auth_user表中有个字段【is_superuser】，值为1或0
            login(request, user)
            return JsonResponse(
                {
                    "ret": 0,
                    "usertype": user.usertype,
                    "userid": user.id,
                    "realname": user.realname,
                }, json_dumps_params={'ensure_ascii': False}
            )
        else:
            return JsonResponse({'ret': 1, 'msg': '用户已经被禁用'}, json_dumps_params={'ensure_ascii': False})
    else:
        return JsonResponse({'ret': 1, 'msg': '用户名或者密码错误'}, json_dumps_params={'ensure_ascii': False})

# 登出
def signout(request):
    logout(request)
    return JsonResponse({'ret': 0})

